<?php
declare (strict_types = 1);
namespace app\api\logic;
use app\admin\model\Config as configModel;
use app\admin\model\Recharge;
class RechargeLogic
{	
	//我的充值记录
	function my($args = []){
		  $res = Recharge::where(['shop_id'=>$args['shop_id'],'user_id'=>$args['uid'],'status'=>1])->order("time desc")->select();
		  return $res;
	}

	function order($args = []){
			$money = $args['money'] ?? 0;
			$ordernum = "R".time().rand(10000,99999);
			if($money<=0){
				 return ['code'=>100,'back_type'=>1,'msg'=>'充值金额异常']; 
			}
			$order = [];
			$order['money'] = $money;
			$order['user_id'] = $args['uid'];
			$order['shop_id'] = $args['shop_id'];
			$order['time'] = time();
			$order['give_money'] =  $give_money;
			$oid = Recharge::insertGetId($order);
			if($oid){
					return ['code'=>200,'back_type'=>1,'msg'=>'ok',['data'=>$ordernum]]; 
			}else{
					return ['code'=>100,'back_type'=>1,'msg'=>'充值订单生成失败']; 
			}
	}
	function orderpay($args = []){
		 $ordernum = $args['ordernum'] ?? '';
		 if($ordernum){
		 	 $order = Recharge::where(['ordernum'=>$ordernum,'shop_id'=>$args['shop_id']])->find();
		 	 if($order['status'] == 0){
		 	 	  		$user_wx_openid = Db::name("user")->where("id",$args['uid'])->value("wx_openid");
						if(empty($user_wx_openid)){
							 return ['code'=>100,'back_type'=>1,'msg'=>'无效用户'];
						}

						$cs = configModel::getShopSettings($args['shop_id']); //获取店铺相关配置

						header("Content-type:text/html;charset=utf-8");
			            $obj = array();
			            $obj['openid'] = $user_wx_openid;
			            $obj['appid'] = $cs['xcx_appid'];
			            $obj['mch_id'] = $cs['wxpay_merchant_id'];
			            $obj['body'] = "账号充值";
			            $obj['out_trade_no'] = $ordernum;
			            $obj['total_fee'] = $order['money'] * 100;
			            $obj['spbill_create_ip'] = $_SERVER['REMOTE_ADDR'];
			            $obj['notify_url'] = "/index/Index/wxnoticy";
			            $obj['trade_type'] = "JSAPI";
			            $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
			            $apikey = $cs['wxpay_api_key'];
			            Vendor("Wxhb.Wxpay");
			            $res = new \Wxpay();
			            $x = $res->pay($url, $obj, $apikey);
			            $arr = $this->xmlToArray($x);
			            if ($arr['return_code'] == "SUCCESS") {

			                $arr['apikey'] = $apikey;
			                $arr['appid'] = $shop['app_id'];

			                return ['code'=>200,'back_type'=>1,'msg'=>'ok',['data'=>$arr]];

			            } else {
			            	return ['code'=>100,'back_type'=>1,'msg'=> "充值失败，请稍后重试,错误信息：" . $arr['return_msg']];
			            }

		 	 }else{
		 	 	 return ['code'=>100,'back_type'=>1,'msg'=>'充值成功，请勿重复操作！']; 
		 	 }
		 }else{
		 	 return ['code'=>100,'back_type'=>1,'msg'=>'充值错误']; 
		 }
	}
	 
}